﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Xml;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.BLL.Hubs;
using Matrix.MaKaYunShang.DAL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;

namespace Matrix.MaKaYunShang.BLL
{
    public class McMessagesBLL : BaseBLL<McMessagesBLL>
    {
        #region 默认方法

        /// <summary>
        ///     增加一条数据
        /// </summary>
        public int Add(McMessages model)
        {
            return McMessagesDAL.Instance.Add(model);
        }

        /// <summary>
        ///     更新一条数据
        /// </summary>
        public bool Update(McMessages model)
        {
            return McMessagesDAL.Instance.Update(model);
        }

        /// <summary>
        ///     删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {
            return McMessagesDAL.Instance.Delete(Id);
        }

        /// <summary>
        ///     批量删除一批数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            return McMessagesDAL.Instance.DeleteList(Idlist);
        }

        /// <summary>
        ///     得到一个对象实体
        /// </summary>
        public McMessages GetModel(int Id)
        {
            DataSet ds = McMessagesDAL.Instance.GetModel(Id);
            return ds == null ? null : ServicesHelper.DataSetToIList<McMessages>(ds).ToList()[0];
        }

        /// <summary>
        ///     获得数据列表
        /// </summary>
        public List<McMessages> GetModelList(string strWhere = null)
        {
            DataSet ds = McMessagesDAL.Instance.GetList(strWhere);
            return ServicesHelper.DataSetToIList<McMessages>(ds).ToList();
        }

        #endregion

        #region 扩展方法

        /// <summary>
        /// 消息推送业务逻辑
        /// </summary>
        /// <param name="shopId">店铺ID</param>
        /// <param name="pushingMsgType">1. 新订单， 2.催单</param>
        /// <param name="orderNo">订单号 给什么显示什么</param>
        /// <param name="wxUserOpenId">微信用户ID / 微信用户名称 给什么显示什么</param>
        /// <param name="mcAccountId">指定发送给商家后台账户</param>
        /// <returns></returns>
        public bool PushingMsg(int shopId, int pushingMsgType, string orderNo, string wxUserOpenId, string mcAccountId = "")
        {
            string title = string.Empty;
            string contents = string.Empty;

            bool templateResult = RetrieveMessageTemplate(pushingMsgType, orderNo, wxUserOpenId, ref title, ref contents);
            
            if (!templateResult) return false;

            bool msgSavingResult = SaveMsgForPushingToShop(title, contents, shopId, orderNo);

            if (!msgSavingResult) return false;

            var alertModel = new McMessageAlertDto
            {
                ShopId = shopId,
                MsgTitle = title,
                MsgContent = contents,
                McAccountId = mcAccountId
            };

            NotificationHub.Client.NewMessage(alertModel);
            return true;
        }

        /// <summary>
        /// 消息存储
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="shopId"></param>
        /// <param name="orderNo"></param>
        /// <returns></returns>
        private bool SaveMsgForPushingToShop(string title, string content, int shopId, string orderNo)
        {
            var orderId = 0;
            var orderInfo = OrdersBLL.Instance.GetOrderInfo(orderNo);
            if (orderInfo != null && orderInfo.Id > 0)
            {
                orderId = orderInfo.Id;
            }

            var msgModel = new McMessages
            {
                MsgCate = 1,
                MsgType = 1,
                Title = title,
                Breif = content.TruncateTo(20),
                Body = content,
                SendToGroup = true, // Send to a Shop, so the all shops account share one message
                Created = DateTime.Now,
                Updated = DateTime.Now,
                CreatedBy = 0,
                UpdatedBy = 0,
                OrderId = orderId
            };

            int msgId = Add(msgModel);

            if (msgId > 0)
            {
                var msgRecModel = new McMessageRecipients
                {
                    MsgId = msgId,
                    ReceiverId = shopId,
                    IsRead = false,
                    MsgCate = msgModel.MsgCate,
                    MsgType = msgModel.MsgType,
                    Created = msgModel.Created,
                    CreatedBy = msgModel.CreatedBy,
                    Updated = msgModel.Updated,
                    UpdatedBy = msgModel.UpdatedBy
                };

                int msgRecId = McMessageRecipientsBLL.Instance.Add(msgRecModel);
                if (msgRecId > 0)
                    return true;
            }

            return false;
        }

        /// <summary>
        /// 获取消息模板
        /// </summary>
        /// <param name="intPushType"></param>
        /// <param name="orderNo"></param>
        /// <param name="wxUserOpenId"></param>
        /// <param name="title"></param>
        /// <param name="contents"></param>
        /// <returns></returns>
        private bool RetrieveMessageTemplate(int intPushType, string orderNo, string wxUserOpenId, ref string title,
            ref string contents)
        {
            try
            {
                var xmlDoc = new XmlDocument();
                string xmlPath = ConfigLib.GetAppSettings("MessageTempalte");
                xmlDoc.Load(xmlPath);

                if (xmlDoc.DocumentElement == null) return false;

                switch (intPushType)
                {
                    case 1:
                    {
                        XmlNode xmlNode1 = xmlDoc.SelectSingleNode("/MessageAlert/NewOrderAlert/Title");
                        XmlNode xmlNode2 = xmlDoc.SelectSingleNode("/MessageAlert/NewOrderAlert/Content");
                        if (xmlNode1 != null) title = xmlNode1.InnerText;
                        if (xmlNode2 != null)
                            contents =
                                xmlNode2.InnerText.Replace("{datetime}", DateTime.Now.ToShortDateString())
                                    .Replace("{wxUserOpenId}", wxUserOpenId)
                                    .Replace("{orderNumber}", orderNo);
                    }
                        break;
                    case 2:
                    {
                        XmlNode xmlNode1 = xmlDoc.SelectSingleNode("/MessageAlert/OrderReminderAlert/Title");
                        XmlNode xmlNode2 = xmlDoc.SelectSingleNode("/MessageAlert/OrderReminderAlert/Content");
                        if (xmlNode1 != null) title = xmlNode1.InnerText;
                        if (xmlNode2 != null) contents = xmlNode2.InnerText.Replace("{orderNumber}", orderNo);
                    }
                        break;
                    case 3:
                        {
                            XmlNode xmlNode1 = xmlDoc.SelectSingleNode("/MessageAlert/AssignOrderAlert/Title");
                            XmlNode xmlNode2 = xmlDoc.SelectSingleNode("/MessageAlert/AssignOrderAlert/Content");
                            if (xmlNode1 != null) title = xmlNode1.InnerText;
                            if (xmlNode2 != null) contents = xmlNode2.InnerText.Replace("{orderNumber}", orderNo);
                        }
                        break;
                    default:
                        return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion
    }
}